<?php

namespace App\Observers;

use App\Models\Bet;
use App\Models\GroupUser;
use App\Models\QuizUser;
use App\Repositories\QuizRepository;
use App\Repositories\GroupRepository;
use App\Repositories\StatementRepository;
use Illuminate\Support\Facades\DB;

class BetObserver
{

    /**
     * @param Bet $bet
     */
    public function creating(Bet $bet)
    {
        $bet->user()->associate(request()->user());
        $bet->quiz()->associate($bet->quizItem->quiz);
        $bet->account()->associate($bet->quizItem->quiz->currentUserAccountInThisGroup);

        $bet->quiz_item_name = $bet->quizItem->name;
        $bet->odds = $bet->quizItem->odds;
        $bet->status = QuizRepository::BET_STATUS_PROCESSED;
    }

    /**
     * @param Bet $bet
     */
    public function created(Bet $bet)
    {
        QuizUser::updateOrCreate([
            'quiz_id' => $bet->quiz_id,
            'user_id' => $bet->user_id,
        ], ['updated_at' => now()]);

        // todo: 增加参加次数

        $this->updated($bet);
    }

    /**
     * @param Bet $bet
     */
    public function updated(Bet $bet)
    {
        switch ($bet->status) {
            case QuizRepository::BET_STATUS_CANCELED:
                // 下注取消恢复铜币
                GroupRepository::incrementCopper($bet->group_user_id, $bet->copper);
                StatementRepository::recordBet($bet, 'cancel');
                break;
            case QuizRepository::BET_STATUS_PROCESSED:
                // 下注成功减少铜币
//                GroupRepository::decrementCopper($bet->group_user_id, $bet->copper);
                $bet->account->update([
                    'join_count' => DB::raw('join_count + 1'),
                    'copper' => DB::raw("copper - {$bet->copper}"),
                ]);
                StatementRepository::recordBet($bet, 'processed', false);
                break;
            case QuizRepository::BET_STATUS_FINISHED:
                // 开奖后增加相应的铜币
                $updateData = [
                    'copper' => DB::raw("copper + $bet->copper_result"),
                    'announce_count' => DB::raw("announce_count + 1"),
                ];
                if (in_array($bet->result, QuizRepository::$quizItemWinResults)) {
                    $updateData['win_count'] = DB::raw("win_count + 1");
                }
                GroupUser::where('id', $bet->group_user_id)->update($updateData);
                StatementRepository::recordBet($bet, 'finished', true, 'copper_result');
                break;
        }
    }
}
